<template>
  <div class="docx-converter">
    <div class="container">
      <div class="header">
        <h1>
          <img src="https://free-1325650170.cos.ap-guangzhou.myqcloud.com/free_convert/freeconvert-logo.svg" alt="FreeConvert Logo" class="logo-icon" />
          DOCX 转 PDF 在线工具
        </h1>
        <p class="subtitle">上传 Word 文档，即可生成高质量 PDF</p>
      </div>

      <div class="upload-section">
        <div
          v-if="!selectedFile"
          class="upload-area"
          :class="{ 'drag-over': dragOver }"
          @drop.prevent="handleDrop"
          @dragover.prevent="dragOver = true"
          @dragleave.prevent="dragOver = false"
        >
          <input ref="fileInput" type="file" accept=".doc,.docx,.odt,.rtf" @change="handleFileSelect" hidden />
          <div class="upload-placeholder">
            <div class="upload-icon">📁</div>
            <p class="upload-text">点击选择或拖拽 DOCX/Word 文档到这里</p>
            <p class="upload-hint">支持 DOC、DOCX、ODT、RTF，最大30MB</p>
            <button class="select-btn" @click="triggerSelect">选择文件</button>
          </div>
        </div>

        <div v-else class="workbench">
          <section class="preview-section">
            <div class="document-preview-wrapper">
              <div class="document-preview">
                <div class="doc-icon">📄</div>
                <div class="doc-text">
                  <p class="file-name">{{ selectedFile.name }}</p>
                  <p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
                  <p class="file-type">{{ selectedFile.type || '未识别类型' }}</p>
                </div>
              </div>
            </div>

            <div class="file-info">
              <p><strong>大小：</strong>{{ formatFileSize(selectedFile.size) }}</p>
              <p><strong>修改时间：</strong>{{ formatDate(selectedFile.lastModified) }}</p>
              <p><strong>说明：</strong>转换过程中会自动嵌入字体并保留书签。</p>
              <!-- <button class="change-btn" @click="triggerSelect">重新选择文件</button> -->
            </div>
          </section>

          <aside class="options-section">
            <h3>转换设置</h3>
            <label class="option-item">
              <input type="checkbox" v-model="options.pdfa" />
              <span>生成 PDF/A（电子归档标准）</span>
            </label>
            <label class="option-item">
              <input type="checkbox" v-model="options.embedStandardFonts" />
              <span>嵌入标准字体，保证跨设备显示一致</span>
            </label>
            <label class="option-item">
              <input type="checkbox" v-model="options.exportBookmarks" />
              <span>保留 Word 书签为 PDF 目录</span>
            </label>
            <button class="convert-btn" :disabled="isUploading" @click="handleConvert">
              <span v-if="!isUploading">开始转换</span>
              <span v-else class="converting-content">
                <span class="spinner-small"></span> 转换中...
              </span>
            </button>
          </aside>

          <div class="mobile-convert-btn-wrapper">
            <button class="mobile-convert-btn" :disabled="isUploading" @click="handleConvert">
              <span v-if="!isUploading">开始转换</span>
              <span v-else class="converting-content">
                <span class="spinner-small"></span> 转换中...
              </span>
            </button>
          </div>
        </div>
      </div>

      <section class="tips-card">
        <h3>为什么选择 FreeConvert DOCX 转 PDF？</h3>
        <ul>
          <li>兼容 Word 中的样式、分页、表格与图片</li>
          <li>可选 PDF/A，满足归档、公文等严格场景</li>
          <li>后端直接调用 LibreOffice，本地处理更安全</li>
        </ul>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { uploadDocxToPdf } from '@/api/conversion'
import { toastError, toastSuccess } from '@/utils/toast'

const router = useRouter()

const fileInput = ref(null)
const selectedFile = ref(null)
const dragOver = ref(false)
const isUploading = ref(false)

const options = ref({
  pdfa: false,
  embedStandardFonts: true,
  exportBookmarks: true,
})

const triggerSelect = () => {
  fileInput.value?.click()
}

const validateFile = (file) => {
  const allowed = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword', 'application/vnd.oasis.opendocument.text', 'application/rtf', 'text/rtf']
  if (!allowed.includes(file.type) && !file.name.toLowerCase().match(/\.(docx|doc|odt|rtf)$/)) {
    toastError('仅支持 DOC、DOCX、ODT、RTF 文档')
    return false
  }
  const maxSize = 30 * 1024 * 1024
  if (file.size > maxSize) {
    toastError('文件不能超过 30MB')
    return false
  }
  return true
}

const handleFileSelect = (e) => {
  const file = e.target.files?.[0]
  if (file && validateFile(file)) {
    selectedFile.value = file
  }
}

const handleDrop = (e) => {
  dragOver.value = false
  const file = e.dataTransfer.files?.[0]
  if (file && validateFile(file)) {
    selectedFile.value = file
  }
}

const clearFile = () => {
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const formatFileSize = (size) => {
  if (!size) return '0 B'
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`
  return `${(size / (1024 * 1024)).toFixed(2)} MB`
}

const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString()
}

const handleConvert = async () => {
  if (!selectedFile.value) {
    toastError('请先选择文件')
    return
  }
  if (isUploading.value) return

  const formData = new FormData()
  formData.append('file', selectedFile.value)
  formData.append('pdfa', options.value.pdfa)
  formData.append('embedStandardFonts', options.value.embedStandardFonts)
  formData.append('exportBookmarks', options.value.exportBookmarks)

  isUploading.value = true
  try {
    const res = await uploadDocxToPdf(formData)
    sessionStorage.setItem('docxToPdfResult', JSON.stringify(res.data))
    toastSuccess('转换成功')
    router.push('/docx-pdf-success')
  } catch (error) {
    toastError(error.message || '转换失败，请稍后重试')
  } finally {
    isUploading.value = false
  }
}
</script>

<style scoped>
.docx-converter {
  min-height: 100vh;
  width: 100vw;
  background: #f5f7fa;
  position: relative;
  overflow: hidden;
  margin: 0;
  padding: 0;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
}

.container {
  width: 100%;
  max-width: 1100px;
  margin: 0 auto;
  padding: 24px 2vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  box-sizing: border-box;
  background: none;
}

.header {
  text-align: center;
  color: #1e293b;
  margin-bottom: 16px;
  animation: fadeInUp 0.8s ease-out;
  flex-shrink: 0;
}

.header h1 {
  font-size: 2rem;
  margin-bottom: 6px;
  font-weight: 700;
  letter-spacing: -0.02em;
  color: #1e293b;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.logo-icon {
  width: 240px;
  height: 180px;
  animation: fadeInUp 0.8s ease-out;
}

.subtitle {
  font-size: 0.9rem;
  color: #64748b;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.4;
}

.upload-section {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  width: 100%;
  max-width: 100%;
  animation: fadeInUp 0.6s ease-out both;
  box-sizing: border-box;
  overflow: visible;
  min-height: auto;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 3rem 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafbfc;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #667eea;
  background: #f0f4ff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
}

.upload-icon {
  font-size: 3.5rem;
  margin-bottom: 0.5rem;
}

.upload-text {
  font-size: 1.1rem;
  font-weight: 600;
  color: #374151;
}

.upload-hint {
  color: #6b7280;
  font-size: 0.875rem;
}

.select-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 0.75rem 2rem;
  border-radius: 8px;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.select-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.workbench {
  width: 100%;
  background: white;
  border-radius: 18px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: grid;
  grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
  gap: 24px;
  align-items: start;
  box-sizing: border-box;
  overflow: hidden;
}

.preview-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.document-preview-wrapper {
  background: #f9fafb;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
}

.document-preview {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  width: 100%;
}

.doc-icon {
  font-size: 3rem;
}

.doc-text {
  flex: 1;
  min-width: 0;
}

.doc-text .file-name {
  font-size: 1.05rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px;
  word-break: break-word;
}

.doc-text .file-size,
.doc-text .file-type {
  margin: 2px 0;
  color: #6b7280;
  font-size: 0.9rem;
  word-break: break-all;
  white-space: normal;
}

.file-info {
  background: #fafbfc;
  padding: 20px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  font-size: 0.95rem;
  color: #4b5563;
  width: 100%;
  box-sizing: border-box;
}

.file-info p {
  margin: 6px 0;
  word-break: break-all;
}

.change-btn {
  margin-top: 12px;
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid #d1d5db;
  background: white;
  cursor: pointer;
  font-size: 0.9rem;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.options-section {
  background: #fafbfc;
  padding: 1.5rem;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  box-sizing: border-box;
  width: 100%;
}

.options-section h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #1f2937;
  font-size: 1.1rem;
  font-weight: 600;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #374151;
  font-size: 0.95rem;
  margin-bottom: 0.9rem;
}

.convert-btn {
  width: 100%;
  white-space: normal;
  line-height: 1.4;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: none;
  padding: 0.875rem;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 1rem;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25);
}

.convert-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.convert-btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(16, 185, 129, 0.4);
}

.converting-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.spinner-small {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 0.6s linear infinite;
}

.mobile-convert-btn-wrapper {
  display: none;
}

.tips-card {
  margin-top: 20px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 6px 20px rgba(15, 23, 42, 0.05);
  width: 100%;
  box-sizing: border-box;
}

.tips-card h3 {
  margin-top: 0;
  margin-bottom: 12px;
  color: #111827;
}

.tips-card ul {
  margin: 0;
  padding-left: 18px;
  color: #4b5563;
  line-height: 1.8;
}

@media (max-width: 1024px) {
  .workbench {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

/* 768px 以下移动端 CSS */
@media (max-width: 768px) {
  .container {
    padding: 12px 3vw;
    min-height: auto;
    padding-bottom: 140px;
  }

  .header {
    margin-bottom: 12px;
  }

  .header h1 {
    font-size: 1.3rem;
    flex-direction: column;
    gap: 8px;
  }

  .logo-icon {
    width: 120px;
    height: 90px;
  }

  .subtitle {
    font-size: 0.85rem;
    padding: 0 8px;
  }

  .upload-section {
    padding: 16px;
    border-radius: 12px;
    overflow: visible;
    min-height: auto;
    padding-bottom: 160px;
  }

  .upload-area {
    padding: 1.5rem 1rem;
    border-radius: 8px;
  }

  .upload-placeholder {
    gap: 0.75rem;
    width: 100%;
  }

  .upload-icon {
    font-size: 2.5rem;
    margin-bottom: 0.5rem;
  }

  .upload-text {
    font-size: 1rem;
  }

  .upload-hint {
    font-size: 0.8rem;
  }

  .select-btn {
    padding: 10px 20px;
    font-size: 0.9rem;
    margin-top: 8px;
    width: 100%;
  }

  .workbench {
    padding: 16px;
    padding-bottom: 80px;
    gap: 16px;
    border-radius: 16px;
    grid-template-columns: 1fr;
  }

  .document-preview-wrapper,
  .file-info,
  .options-section {
    border-radius: 16px;
  }

  .file-info {
    margin-bottom: 80px;
  }

  .options-section {
    order: -1;
  }

  .mobile-convert-btn-wrapper {
    display: block;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    padding: 12px 16px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
    border-top: 1px solid rgba(102, 126, 234, 0.1);
  }

  .mobile-convert-btn {
    width: 100%;
    padding: 16px 24px;
    font-size: 1.05rem;
    font-weight: 600;
    color: white;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border: none;
    border-radius: 12px;
    cursor: pointer;
    box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
    white-space: normal;
    line-height: 1.4;
  }

  .change-btn {
    width: 100%;
  }

  .mobile-convert-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .tips-card {
    padding: 18px;
  }

  /* 隐藏 aside 配置卡片里的按钮，只显示底部按钮 */
  .workbench .convert-btn {
    display: none !important;
  }
}

@media (max-width: 540px) {
  .container {
    padding: 8px 2vw;
    padding-bottom: 90px;
  }

  .header h1 {
    font-size: 1.2rem;
  }

  .upload-section {
    padding: 12px;
    padding-bottom: 130px;
  }

  .upload-area {
    padding: 24px 16px;
  }

  .workbench {
    padding: 14px;
  }

  .document-preview {
    gap: 12px;
  }

  .options-section {
    padding: 14px;
  }

  .tips-card {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .logo-icon {
    width: 140px;
    height: 80px;
  }

  .file-info {
    font-size: 0.85rem;
  }

  .doc-text .file-name {
    font-size: 1rem;
  }

  .options-section {
    padding: 12px;
  }

  .tips-card {
    padding: 14px;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>

